//
//  TestDB.m
//  test
//
//  Created by mac on 2017/9/15.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "TestDB.h"

@implementation TestDB
{
    //数据库对象
    FMDatabaseQueue *queue;
}
//获取单例对象
+(TestDB *)instance
{
    static TestDB *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        manager=[[TestDB alloc]init];
    });
    return manager;
}

-(instancetype)init
{
    if(self=[super init])
    {
        //初始化数据库对象
        [self createDataBase];
    }
    return self;
}


-(void)createDataBase
{
    
    //数据库文件的路径
    NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/product.sqlite"];
    NSLog(@"pat=%@",path);
    
    queue=[FMDatabaseQueue databaseQueueWithPath:path];
    
    [queue inDatabase:^(FMDatabase *db) {
        //创建表
        BOOL createTableResult=[db executeUpdate:@"create table if not exists product (Id integer primary key autoincrement,report_date varchar(255),post_code varchar(255),store_name varchar(255),brand varchar(255),reason_name varchar(255))"];
        if (createTableResult) {
            NSLog(@"创建表成功");
        }else{
            NSLog(@"创建表失败");
        }
    }];
}

- (IBAction)select{
     NSDate *startTime = [NSDate date];
    [queue inDatabase:^(FMDatabase *db) {
        //获取结果集，返回参数就是查询结果
        FMResultSet *rs=[db executeQuery:@"select brand,count(brand) total from product where report_date='2010-10-10' group by brand"];
        while ([rs next]) {
            //NSLog(@"===%@====%@",[rs stringForColumn:@"brand"],[rs stringForColumn:@"total"]);
        }
        NSDate *endTime = [NSDate date];
        NSTimeInterval a = [endTime timeIntervalSince1970] - [startTime timeIntervalSince1970];
        NSLog(@"查询分类数据用时%f秒",a);
    }];
}

@end
